//
//  DealersViewController.m
//  ZiJinLian
//
//  Created by 🐛 on 2017/12/25.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "DealersViewController.h"
#import "DealersTableViewCell.h"
#import "SetTimeViewController.h"
#import "LMAlertView.h"
#import "TXTimeSelectorViewController.h"
#import "DealerModel.h"
#import "SubmitOrderViewController.h"
#import "PayViewController.h"
@interface DealersViewController ()<UITableViewDelegate,UITableViewDataSource,LMAlertViewdelegate,CLLocationManagerDelegate>

@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) UIButton *lastBtn;
@property (nonatomic ,strong) DealersTableViewCell *lastCell;
@property (nonatomic,strong)LMAlertView*lmAlert;
@property (nonatomic,strong)DealerModel*dealerModel;
@property (nonatomic,strong)NSMutableArray*dealerArray;
@property (nonatomic,assign)int pagNo;
@property (nonatomic, strong) CLLocationManager * locationManager;
@property (nonatomic ,strong) NSString *longitude;
@property (nonatomic ,strong) NSString *latitude;
@property (nonatomic ,strong) NSString *storeId;


@end

@implementation DealersViewController
-(NSMutableArray *)dealerArray{
    if (!_dealerArray) {
        _dealerArray=[NSMutableArray array];
    }
    return _dealerArray;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self startLocation];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"附近经销商";
    [self.view addSubview:self.tableView];
    [self creatBottomBut];
    [self showTempView:@"附近暂无经销商！" Image:@"img_fail_monk" CGFrame:CGRectMake(0, 0, MainW,MainH-64)];
    self.tempView.hidden=YES;
    // Do any additional setup after loading the view.
}
-(void)creatBottomBut{
    //到店
    UIButton *getBtn=[[UIButton alloc]initWithFrame:CGRectMake(MainW/2, MainH-50-64, MainW/2, 50)];
    [getBtn setTitle:@"到店" forState:0];
    [getBtn setBackgroundColor:Red_Color];
    [getBtn addTarget:self action:@selector(opretionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    getBtn.titleLabel.font=FontAndStyle15;
    getBtn.tag=10;
    [self.view addSubview:getBtn];
    //直邮
    UIButton *logBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, MainH-50-64, MainW/2, 50)];
    logBtn.titleLabel.font=FontAndStyle15;
    [logBtn setTitle:@"直邮" forState:0];
    [logBtn setBackgroundColor:[UIColor colorWithHexString:@"#e65103"]];
    [logBtn addTarget:self action:@selector(opretionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    logBtn.tag=20;
    [self.view addSubview:logBtn];
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, MainW, MainH-64-50) style:UITableViewStylePlain];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.tableFooterView=[UIView new];
        _tableView.separatorColor=SeparatorColor;
        _tableView.separatorInset=UIEdgeInsetsZero;
        _tableView.backgroundColor=Gray_Color;
        [_tableView registerNib:[UINib nibWithNibName:@"DealersTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"DealersTableViewCell"];
        _tableView.mj_footer=[MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            self.pagNo++;
            [self loadRequestDealers];
        }];
        
    }
    return _tableView;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dealerArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DealersTableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:@"DealersTableViewCell"];
//    [cell.selectBtn addTarget:self action:@selector(seletDealerClick:) forControlEvents:UIControlEventTouchUpInside];
    DealerModel*model=self.dealerArray[indexPath.row];
    cell.selectBtn.tag=indexPath.row;
    /*@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
     @property (weak, nonatomic) IBOutlet UILabel *addressLabel;
     @property (weak, nonatomic) IBOutlet UILabel *numberLabel;
     @property (weak, nonatomic) IBOutlet UIButton *selectBtn;*/
//    cell.nameLabel.text=model.name;
//    cell.addressLabel.text=model.area;
//    cell.numberLabel.text=model.phone;
	 cell.model = model;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 85;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    DealersTableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
//    if (self.lastCell!=cell) {
//        cell.selectBtn.selected=YES;
//        self.lastCell.selectBtn.selected=NO;
//        self.lastCell=cell;
//    }else{
//        cell.selectBtn.selected=YES;
//    }
//    DealerModel*model=self.dealerArray[indexPath.row];
	for (int i = 0; i<self.dealerArray.count; i++) {
		DealerModel *model = self.dealerArray[i];
		if (i == indexPath.row) {
			BOOL tmp = model.isSelect;
			model.isSelect = !tmp;
			if (model.isSelect) {
				self.storeId=model.storeId;
			}else{
				self.storeId=@"0";

			}
		}else{
			model.isSelect = NO;
		}
	}
	[self.tableView reloadData];
	
}
//-(void)seletDealerClick:(UIButton *)sender{
//    if (self.lastBtn!=sender) {
//        self.lastBtn.selected=NO;
//        self.lastBtn=sender;
//    }else{
//        sender.selected=YES;
//    }
//    DealerModel*model=self.dealerArray[sender.tag];
//    self.storeId=model.storeId;
//
//}
-(void)opretionBtnClick:(UIButton *)sender{
    
    if (sender.tag==20) {
        if (self.storeId==nil || [self.storeId isEqualToString:@"0"]) {
            [self showToast:@"请选择门店"];
            return;
        }
		
		NSString *storeName;
		for (int i = 0; i<self.dealerArray.count; i++) {
			DealerModel *model = self.dealerArray[i];
			if (model.isSelect) {
				storeName = model.name;
				break;
			}
		}
		
        NSMutableDictionary*dic=[NSMutableDictionary dictionary];
        dic[@"storeId"]=self.storeId;
        dic[@"deliveryType"]=@"MAIL";
        dic[@"paymentType"]=@"FULL";
        LXAlertView *alert=[[LXAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:@"直邮是由该厂经销商(%@)以厂家经销价为您配货",storeName] cancelBtnTitle:@"取消" otherBtnTitle:@"确定" clickIndexBlock:^(NSInteger clickIndex) {
            if (clickIndex==1) {
                SubmitOrderViewController*vc=[[SubmitOrderViewController alloc]init];
                vc.orderDic=self.orderDic;
                vc.styple=NearBuy;
                vc.nearDic=dic;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }];
        [alert showLXAlertView];
    }else{
        if (self.storeId==nil) {
            [self showToast:@"请选择门店"];
            return;
        }
        self.lmAlert=[[LMAlertView alloc]init];
        self.lmAlert.delegate=self;
        [self.view addSubview:self.lmAlert];
        
    }
}
-(void)chooseTimeClick{
    TXTimeSelectorViewController *tc = [[TXTimeSelectorViewController alloc]initWithShowFrame:CGRectMake(0 , MainH - (MainH/3),MainW, MainH/3) ShowStyle:MYPresentedViewShowStyleFromBottomSpreadStyle callback:^(NSString  *result) {
        NSLog(@"time --> %@",result);
        [self.lmAlert.setTime setTitle:result forState:UIControlStateNormal];
        NSNotification *notification =[NSNotification notificationWithName:@"timeSet" object:result userInfo:nil];
        // 3.通过 通知中心 发送 通知
        [[NSNotificationCenter defaultCenter] postNotification:notification];
    }];
    
    tc.mode = UIDatePickerModeDateAndTime;
    [self presentViewController:tc animated:YES completion:^{
        [self.lmAlert sendSubviewToBack:tc.view];
    }];
}
-(void)resultClick:(NSMutableDictionary *)infoDic{
    
    NSMutableDictionary*dic=[NSMutableDictionary dictionary];
    dic=infoDic;
    dic[@"storeId"]=self.storeId;
    dic[@"deliveryType"]=@"STORE";
    [self nearRequest:self.orderDic NearDic:dic];
//    SubmitOrderViewController*vc=[[SubmitOrderViewController alloc]init];
//    vc.orderDic=self.orderDic;
//    vc.styple=1;
//    vc.nearDic=dic;
//    [self.navigationController pushViewController:vc animated:YES];
}
-(void)loadRequestDealers{
    self.isShowDiag=YES;
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    dic[@"skuId"]=self.factoryId;
    dic[@"lat"]=self.latitude;
    dic[@"lon"]=self.longitude;
    dic[@"pageNumber"]=@(self.pagNo);
    dic[@"pageSize"]=@(10);
    [self doHttpRequestWithApi:NearAgent method:GET dic:dic successBlock:^(NSDictionary *dic) {
        [self.dealerArray addObjectsFromArray:[DealerModel mj_objectArrayWithKeyValuesArray:dic[@"data"][@"list"]]];
        if (self.dealerArray.count==0) {
            self.tempView.hidden=NO;
        }else{
            self.tempView.hidden=YES;
        }
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    }];
}
//定位
-(void)startLocation
{
    if([CLLocationManager locationServicesEnabled])
    {
        // 启动位置更新
        // 开启位置更新需要与服务器进行轮询所以会比较耗电，在不需要时用stopUpdatingLocation方法关闭;
        _locationManager = [[CLLocationManager alloc] init];
        //设置定位的精度
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        _locationManager.distanceFilter = 10.0f;
        _locationManager.delegate = self;
        if ([[[UIDevice currentDevice] systemVersion] floatValue] > 8.0)
        {
            [_locationManager requestAlwaysAuthorization];
            [_locationManager requestWhenInUseAuthorization];
        }
        
        //开始实时定位
        [_locationManager startUpdatingLocation];
    }else {
        //NSLog(@"请开启定位功能！");
    }
}
//代理,定位代理经纬度回调
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation * newLoaction = locations[0];
    CLLocationCoordinate2D oCoordinate = newLoaction.coordinate;
    self.longitude=[NSString stringWithFormat:@"%f",oCoordinate.longitude];
    self.latitude=[NSString stringWithFormat:@"%f",oCoordinate.latitude];
    NSLog(@"执行几次");
    [self.locationManager stopUpdatingLocation];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.dealerArray removeAllObjects];
        self.pagNo=1;
        [self loadRequestDealers];
    });
    
    
}
//附近购
-(void)nearRequest:(NSDictionary *)orderDic NearDic:(NSMutableDictionary *)nearDic{
    
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    dic=nearDic;
    dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
    dic[@"skuId"]=orderDic[@"skus"][0][@"skuId"];
    dic[@"number"]=orderDic[@"skus"][0][@"quantity"];
    dic[@"remark"]=@"";
    //if (self.remarkTf.text.length!=0) {
        dic[@"invoice"]=@"1";
//    }else{
//        dic[@"invoice"]=@"0";
//    }
    
    [self doHttpRequestWithApi:API_SubmitOrderNow method:POST dic:dic successBlock:^(NSDictionary *dic) {
        NSLog(@"提交订单 %@",dic);
        PayViewController *vc=[[PayViewController alloc]init];
        vc.orderSn=[NSString stringWithFormat:@"%@",dic[@"data"][@"payNo"]];
        vc.orderDic=[dic[@"data"] copy];
        vc.isNear=YES;
        [self.navigationController pushViewController:vc animated:YES];
        
        
    }];
}
@end
